package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"jingdong-product/models/mysql"

	"jingdong-product/productrpc/internal/svc"
	"jingdong-product/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductUpdateLogic {
	return &ProductUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductUpdateLogic) ProductUpdate(in *productrpc.ProductUpdateRequest) (*productrpc.ProductUpdateResponse, error) {
	// todo: add your logic here and delete this line
	var productFind mysql.Product
	mysql.DB.Debug().Where("id = ?", in.ProductId).Find(&productFind)
	if productFind.ID == 0 {
		return nil, fmt.Errorf("该商品不存在，禁止更新")
	}
	product := mysql.Product{
		Model:        gorm.Model{ID: uint(in.ProductId)},
		ProductTitle: in.ProductTitle,
		ProductImage: in.ProductImage,
		ProductPrice: float64(in.ProductPrice),
		ProductDesc:  in.ProductDesc,
		UserId:       int(in.UserId),
	}
	err := mysql.DB.Debug().Updates(&product).Error
	if err != nil {
		return nil, fmt.Errorf("更新成功")
	}
	return &productrpc.ProductUpdateResponse{
		ProductId: int64(productFind.ID),
	}, nil
}
